<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
  import echarts from 'echarts'
  import china from '@/utils/china.json'
  import {debounce} from '@/utils'


  export default {
    props: {
      statistics: {
        type: Object,
        'default': {}
      },
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '600px'
      }
    },
    data() {
      return {
        chart: null
      }
    },
    watch: {
      statistics: function (newVal) {
        if (Object.keys(newVal).length !== 0) {
          this.initChart(newVal);
        }
      }
    },
    mounted() {
      this.__resizeHandler = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100);
      window.addEventListener('resize', this.__resizeHandler);
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHandler)
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart(statistics) {
        echarts.registerMap('china', china);
        this.chart = echarts.init(this.$el);
        this.chart.on('click', this.echartsMapClick);
        let dataVal = [];
        for (let key in statistics.summary) {
          let item = {
            name: key,
            value: statistics.summary[key].total
          };
          dataVal.push(item);
        }
        this.chart.setOption({
          title: {
            text: '网关地域分布图',
            // subtext: '纯属虚构',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: ['网关数']
          },
          visualMap: {
            min: 0,
            max: 2500,
            left: 'left',
            top: 'bottom',
            text: ['高', '低'], // 文本，默认为数值文本
            calculable: true
          },
          series: [
            {
              name: '网关数',
              type: 'map',
              mapType: 'china',
              // roam: true,
              zoom: 1.6,
              top: 150,
              label: {
                // show: true
              },
              data: dataVal
            }
          ]
        })
      },
      echartsMapClick(params) {
        this.$router.push({
          name: 'remote',
          query: { name: params.name }
        });
      }
    }
  }
</script>
